package me.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class Demo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		// String commend = sc.nextLine();
		System.out.println("waiting for input");
		try {
			handler(sc.nextLine());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void handler(String commend) throws IOException {

		String[] parsed = commend.split(" ");

		if ("copy".equals(parsed[0])) {
			copy(parsed);
		}
		if ("cat".equals(parsed[0])) {
			cat(parsed);
		}
		if ("cat2".equals(parsed[0])) {
			cat2(parsed);
		}
		

	}

	public static void cat2(String[] parsed) {
		File file = new File(parsed[1]);
		FileInputStream fis = null;
		InputStreamReader isr = null;
		OutputStreamWriter opw = new OutputStreamWriter(System.out);

		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, "utf-8");
			char[] temp = new char[1024];
			int flag;

			while (-1 != (flag = isr.read(temp))) {
				opw.write(temp, 0, flag);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void cat(String[] parsed) {
		File file = new File(parsed[1]);
		FileInputStream fis = null;
		InputStreamReader isr = null;

		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, "utf-8");
			char[] temp = new char[1024];
			int flag;
			String s = "";
			while (-1 != (flag = isr.read(temp))) {
				s += new String(temp, 0, flag);
			}
			System.out.print(s);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void copy(String[] parsed) throws IOException {
		File source = new File(parsed[1]);
		File target = new File(parsed[2]);
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(source);
			fos = new FileOutputStream(target);
			byte[] temp = new byte[1024];
			int flag;
			while (-1 != (flag = fis.read(temp))) {
				fos.write(temp, 0, flag);
			}

		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != fis) {
				fis.close();
			}
			if (null != fos) {
				fos.close();
			}
		}

	}
}